package cn.toma.common.converter;

import cn.toma.common.enumtype.status.IEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * @Author: zqx
 * @Date: 2019-08-02 15:02
 * @Description: 枚举工厂转换类
 */
public class EnumConvertFactory implements ConverterFactory<String, IEnum>
{

	private static final Map<Class, Converter> converterMap = new WeakHashMap<>();

	@Override
	public <T extends IEnum> Converter<String, T> getConverter(Class<T> aClass)
	{
		Converter result = converterMap.get(aClass);
		if (result == null) {
			result = new IntegerStrToEnum<T>(aClass);
			converterMap.put(aClass, result);
		}
		return result;

	}

	class IntegerStrToEnum<T extends IEnum> implements Converter<String, T>
	{
		private final Class<T> enumType;
		private Map<String, T> enumMap = new HashMap<>();

		public IntegerStrToEnum(Class<T> enumType)
		{
			this.enumType = enumType;
			T[] enums = enumType.getEnumConstants();
			for (T e : enums) {
				enumMap.put(e.getCode().toString() + "", e);
			}
		}


		@Override
		public T convert(String s)
		{
			T result = enumMap.get(s);
			if (result == null) {
				throw new IllegalArgumentException("No element matches " + s);
			}
			return result;
		}
	}


}
